import re
import torch
# from stanfordcorenlp import StanfordCoreNLP
from model.encoders.StanfordCoreNLP_x import *

nlp = StanfordCoreNLP('utils/stanford-corenlp-4.4.0')
device = 'cuda' if torch.cuda.is_available() else 'cpu'


def extract_phrase(data):
    sentence = ""
    if isinstance(data, list):
        for word in data:
            if "http" not in word:
                sentence = sentence + " " + word
    elif isinstance(data, str):
        sentence = data
    else:
        return False

    # 抽取名词
    phrase_temp_list = []
    character = nlp.pos_tag(sentence)
    phrase_list = re.findall(r"['\"](.*?)['\"]", sentence)

    index = 0
    bj = False
    for i in range(len(character)):
        if bj == True:
            if (index + 1) < len(character):
                i = index + 1
            else:
                break
        if "NN" in character[i][1]:
            str_temp = character[i][0]

            index = i + 1
            last = ""
            last_noun = ""
            while index < len(character) and (
                    ("NN" in character[index][1]) or character[index][0] == 'of' or character[index][0] == '.' or
                    character[index][0] == '-' or character[index][0] == '\''):
                str_temp = str_temp + last
                last = ' ' + character[index][0]
                last_noun = character[index][1]
                index = index + 1
            if "NN" in last_noun:
                str_temp = str_temp + last
            phrase_temp_list.append(str_temp)
            bj = True
        else:
            bj = False

    # 后处理
    for i in range(len(phrase_temp_list)):
        phrase_list.append(phrase_temp_list[i])
    for i in range(len(phrase_list)):
        phrase_list[i] = phrase_list[i].strip(" ")

    phrase_index_list = []
    for phrase in phrase_list:
        new_phrase = sentence[:sentence.find(phrase)].replace("\\", "").replace("'", "").replace("\"", "").replace("  ",
                                                                                                                   " ").strip()
        new_word_list = [i for i in new_phrase.split(" ")]
        phrase_word_list = [i for i in phrase.split(" ")]
        phrase_index_list.append([len(new_word_list), len(phrase_word_list)])

    return phrase_list, phrase_index_list
